/**
 * 许可证管理路由
 *
 * Created by snowingsea on 2020/02/24.
 */
// const multer = require('multer');
const middleware = require('./../middleware');
const license = require('./../../models/license');
const PhoenixError = require('./../../models/phoenix-error');
const { fixLicenseStatusResponse } = require('../../helpers/licenseHelper');
// const cacheUtil = require('../../cacheUtil');
const uploadProgress = require('../middleware/upload-progress');

/**
 * 获取许可证信息
 * @param req
 * @param res
 * @param next
 */
function getLicense(req, res, next) { // eslint-disable-line no-unused-vars
  fixLicenseStatusResponse(license.getJson(req.$license))
    .then((resp) => res.json(resp));
}

/**
 * 更换许可证
 * @param req
 * @param res
 * @param next
 */
function replaceLicense(req, res, next) {
  if (!req.file && !req.query.license) {
    next(new PhoenixError('invalid request', 'Missing parameters. "license" or "file" is required'));
    return;
  }

  Promise.resolve()
    .then(() => {
      if (req.file) {
        return license.replaceLicenseByFile(req.file.path);
      }
      return license.replaceLicenseByString(req.query.license);
    })
    .then(() => license.getLicense())
    .then((resLicense) => {
      res.json(license.getJson(resLicense));
    })
    .catch((err) => {
      next(new PhoenixError(err));
    });
}

/**
 * 删除许可证
 * @param req
 * @param res
 * @param next
 */
function removeLicense(req, res, next) {
  license.removeLicense()
    .then(() => {
      res.status(204).json();
    })
    .catch((err) => {
      next(new PhoenixError(err));
    });
}

/**
 * Export model definition object.
 */
module.exports = (app, prefix) => {
  const licenseURL = `${prefix}/license.json`;
  const upload = uploadProgress;

  // 获取许可证
  app.get(licenseURL, middleware.user.requireTokenUnexpired);
  app.get(licenseURL, middleware.user.requireAvailable);
  app.get(licenseURL, middleware.user.requireAdministrator);
  app.get(licenseURL, middleware.license.requireLicenseExist);
  app.get(licenseURL, getLicense);

  // 添加许可证
  app.post(licenseURL, middleware.user.requireTokenUnexpired);
  app.post(licenseURL, middleware.user.requireAvailable);
  app.post(licenseURL, middleware.user.requireAdministrator);
  app.post(licenseURL, upload.single('file'));
  app.post(licenseURL, replaceLicense);

  // 更新许可证
  app.put(licenseURL, middleware.user.requireTokenUnexpired);
  app.put(licenseURL, middleware.user.requireAvailable);
  app.put(licenseURL, middleware.user.requireAdministrator);
  app.put(licenseURL, middleware.license.requireLicenseExist);
  app.put(licenseURL, upload.single('file'));
  app.put(licenseURL, replaceLicense);

  // 删除许可证
  app.delete(licenseURL, middleware.user.requireTokenUnexpired);
  app.delete(licenseURL, middleware.user.requireAvailable);
  app.delete(licenseURL, middleware.user.requireAdministrator);
  app.delete(licenseURL, middleware.license.requireLicenseExist);
  app.delete(licenseURL, removeLicense);
};
